import time
import functools

import numpy as np
import pandas as pd
from tqdm import tqdm
from prophet import Prophet
import matplotlib.pyplot as plt
from sklearn import linear_model
from random import random, randint, choice
from neuralprophet import NeuralProphet

from optimizers.pso import PSO
from data_processing import load_data

data = load_data()


def execution_time(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        func_result = func(*args, **kwargs)
        end_time = time.time()
        print(f'time: {end_time - start_time}')
        return func_result

    return wrapper


def trade(trades, alpha=None):
    if alpha is None:
        alpha = [0.02, 0.01, 0]
    now_cash = 1000
    btc_gold = [0, 0]
    for index, day in enumerate(trades):
        for i, name in enumerate(('btc', 'gold')):
            if np.isnan(data[name][index]):
                continue
            if day[i] < 0:
                change = min(abs(day[i]), btc_gold[i])
                btc_gold[i] -= change
                now_cash += (change * data[name][index]) * (1 - alpha[i])
            else:
                change = min(day[i], now_cash / data[name][index])
                now_cash -= change * data[name][index]
                btc_gold[i] += change * (1 - alpha[i])
        now_cash *= (1 - alpha[2])

    return now_cash + btc_gold[0] * data.loc[data.index[-1]]['btc'] + btc_gold[1] * data.loc[data.index[-1]]['gold']


def opt_stupid():
    def wrapper(trades_list):
        return -trade([trades_list[i:i + 2] for i in range(0, len(trades_list), 2)])

    pso = PSO(wrapper, ndim=3650, lb=[-1000] * 3650, ub=[1000] * 3650)
    print(pso.run())


def prophet():
    df = pd.DataFrame()
    df['ds'] = data['date'][:1000]
    df['y'] = data['btc'][:1000]
    m = Prophet()
    m.fit(df)
    future = m.make_future_dataframe(periods=150)
    forecast = m.predict(future)
    fig1 = m.plot(forecast)
    fig1.savefig('test.png')


@execution_time
def arnet():
    df = pd.DataFrame()
    df['ds'] = data['date'][:1000]
    df['y'] = data['btc'][:1000]
    m = NeuralProphet(
        # n_lags=5,
        # changepoints_range=0.95,
        # n_changepoints=30,
        weekly_seasonality=False
    )

    m.fit(df, freq="D")
    future = m.make_future_dataframe(df, periods=365 * 2, n_historic_predictions=len(df))
    forecast = m.predict(future)
    fig_forecast = m.plot(forecast)
    fig_forecast.show()
    fig_model = m.plot_parameters()
    fig_model.show()


def polynomial():
    from sklearn.preprocessing import PolynomialFeatures
    from sklearn.linear_model import LinearRegression
    from sklearn.pipeline import Pipeline

    model = Pipeline([('poly', PolynomialFeatures(degree=6)),
                      ('linear', LinearRegression(fit_intercept=False))])

    y = np.array(data['btc'][:700])
    x = np.arange(len(y))
    model = model.fit(x[:, np.newaxis], y)
    pre = model.predict(x.reshape(-1, 1))  # noqa
    plt.scatter(x, y)
    plt.plot(x, pre, color='r')
    plt.savefig('test.png')


def run(alpha=None):
    if alpha is None:
        alpha = [0, 0.01, 0.02]
    trades = []
    history = []
    capital_history = []
    cash_gold_btc = [1000, 0, 0]
    fill_data = data.fillna(method='pad')
    pre_days = 25
    for index in tqdm(range(2 + pre_days, len(data))):
        day_trade = [0, 0, 0]
        # get the best day trade info

        today_price = [0, fill_data.loc[index]['gold'], fill_data.loc[index]['btc']]
        sum_price = [0, 0, 0]
        for i in range(index - pre_days, index):
            sum_price[1] += fill_data.loc[i]['gold']
            sum_price[2] += fill_data.loc[i]['btc']
        sum_price[1] /= -pre_days
        sum_price[2] /= -pre_days
        sum_price[1] += today_price[1]
        sum_price[2] += today_price[2]
        # min_price = [0, min(fill_data['gold'][2 + pre_days - 1:index]), min(fill_data['btc'][2 + pre_days - 1:index])]
        max_price = [0, max(fill_data['gold'][index - pre_days:index]), max(fill_data['btc'][index - pre_days:index])]
        temp = (sum_price[1]) / (max_price[1]) / (max_price[1]) * 100 * 5
        day_trade[1] += temp
        temp = (sum_price[2]) / (max_price[2]) / (max_price[2]) * 100 * 5
        day_trade[2] += temp

        # if index == 2:
        #     day_trade = [0, 0, 1000]

        trades.append(day_trade)
        for i, name in enumerate(('gold', 'btc')):
            i += 1
            if np.isnan(data[name][index]):
                continue
            if day_trade[i] < 0:
                change = min(abs(day_trade[i]), cash_gold_btc[i])
                cash_gold_btc[i] -= change
                cash_gold_btc[0] += (change * data[name][index]) * (1 - alpha[i])
            else:
                change = min(day_trade[i], cash_gold_btc[0] / data[name][index])
                cash_gold_btc[0] -= change * data[name][index]
                cash_gold_btc[i] += change * (1 - alpha[i])
        capital_history.append(cash_gold_btc[0] + cash_gold_btc[1] * data.loc[index]['gold'] + \
                               cash_gold_btc[2] * data.loc[index]['btc'])
        cash_gold_btc[0] *= (1 - alpha[0])
        history.append(cash_gold_btc.copy())
    # draw
    plt.figure(figsize=(10, 20))
    plt.subplot(6, 1, 1)
    plt.plot(list(range(2 + pre_days, len(data))), capital_history)
    plt.title('capital')
    for i, name in enumerate(('cash', 'gold', 'btc')):
        plt.subplot(6, 1, i + 2)
        plt.plot(list(range(2 + pre_days, len(data))), list(map(lambda x: x[i], history)))
        plt.title(name)
    plt.subplot(6, 1, 5)
    plt.plot(list(range(2 + pre_days, len(data))), fill_data['gold'][2 + pre_days:])
    plt.title('gold price')
    plt.subplot(6, 1, 6)
    plt.plot(list(range(2 + pre_days, len(data))), fill_data['btc'][2 + pre_days:])
    plt.title('btc price')
    plt.savefig('test.png')

    return capital_history[-1], cash_gold_btc


def proportion_model(alpha=None):
    df_temp = pd.read_csv('temp1.csv')
    if alpha is None:
        alpha = [0, 0.01, 0.02]
    trades = []
    history = []
    capital_history = []
    cash_gold_btc = [1000, 0, 0]
    fill_data = data.fillna(method='pad')
    fill_data['cash'] = [1] * len(fill_data)
    pre_days = 100
    for index in tqdm(range(2 + pre_days, len(data))):
        day_proportion = [0, 0, 0]
        # get the best day trade info

        # today_price = [0, fill_data.loc[index]['gold'], fill_data.loc[index]['btc']]
        # sum_price = [0, 0, 0]
        # for i in range(index - pre_days, index):
        #     sum_price[1] += fill_data.loc[i]['gold']
        #     sum_price[2] += fill_data.loc[i]['btc']
        # sum_price[1] /= -pre_days
        # sum_price[2] /= -pre_days
        # sum_price[1] += today_price[1]
        # sum_price[2] += today_price[2]
        # # min_price = [0, min(fill_data['gold'][2 + pre_days - 1:index]), min(fill_data['btc'][2 + pre_days - 1:index])]
        # max_price = [0, max(fill_data['gold'][2 + pre_days - 1:index]), max(fill_data['btc'][2 + pre_days - 1:index])]
        # temp = (sum_price[1]) / (max_price[1]) / (max_price[1]) * 100
        # day_proportion[1] += temp
        # temp = (sum_price[2]) / (max_price[2]) / (max_price[2]) * 100
        # day_proportion[2] += temp
        day_proportion = [0, df_temp.loc[index][1], df_temp.loc[index][0]]
        pass
        # if index == 2:
        #     day_trade = [0, 0, 1000]
        day_proportion = [max(0, day_proportion[i]) for i in range(3)]

        if np.isnan(data['gold'][index]):
            day_proportion[1] = 0
        total_capital = cash_gold_btc[0] + cash_gold_btc[1] * fill_data.loc[fill_data.index[index]]['gold'] + \
                        cash_gold_btc[2] * fill_data.loc[fill_data.index[index]]['btc']
        day_proportion_sum = sum(day_proportion)
        if day_proportion_sum == 0:
            cash_gold_btc = [total_capital, 0, 0]
        else:
            day_proportion = [day_proportion[i] / day_proportion_sum for i in range(3)]
            cash_gold_btc_new = [0, 0, 0]
            for i, name in enumerate(('cash', 'gold', 'btc')):
                cash_gold_btc_new[i] = day_proportion[i] * total_capital / fill_data[name][index]
                cash_gold_btc_new[i] -= abs(cash_gold_btc_new[i] - cash_gold_btc[i]) * alpha[i]
            cash_gold_btc = cash_gold_btc_new
        cash_gold_btc[0] *= (1 - alpha[0])
        trades.append(day_proportion)
        history.append(cash_gold_btc.copy())
        capital_history.append(total_capital)

    # draw
    plt.figure(figsize=(10, 20))
    plt.subplot(6, 1, 1)
    plt.plot(list(range(2 + pre_days, len(data))), capital_history)
    plt.title('capital')
    for i, name in enumerate(('cash', 'gold', 'btc')):
        plt.subplot(6, 1, i + 2)
        plt.plot(list(range(2 + pre_days, len(data))), list(map(lambda x: x[i], history)))
        plt.title(name)
    plt.subplot(6, 1, 5)
    plt.plot(list(range(2 + pre_days, len(data))), fill_data['gold'][2 + pre_days:])
    plt.title('gold price')
    plt.subplot(6, 1, 6)
    plt.plot(list(range(2 + pre_days, len(data))), fill_data['btc'][2 + pre_days:])
    plt.title('btc price')
    plt.savefig('test.png')

    return cash_gold_btc[0] + cash_gold_btc[1] * data.loc[data.index[-1]]['gold'] + \
           cash_gold_btc[2] * data.loc[data.index[-1]]['btc'], cash_gold_btc


@execution_time
def opt_decision_model(arguments, alpha=None):
    a, b, l1, l2, k1, k2, k3 = arguments
    if alpha is None:
        alpha = [0, 0.01, 0.02]
    trades = []
    history = []
    capital_history = []
    cash_gold_btc = [1000, 0, 0]
    fill_data = data.fillna(method='pad')
    for index in range(0, len(data) - b - 1):
        day_trade = [0, 0, 0]
        # get the best day trade info
        m_list = []
        for i, name in enumerate(('gold', 'btc')):
            mean_short = np.mean(fill_data[name][index + 1:index + 1 + a]) / fill_data[name][index] - 1
            var_short = np.std(fill_data[name][index + 1:index + 1 + a])
            mean_long = np.mean(fill_data[name][index + 1 + a:index + 1 + b]) / fill_data[name][index] - 1
            var_long = np.std(fill_data[name][index + 1 + a:index + 1 + b])
            p_short = l1 * mean_short - l2 * var_short / 100000
            # assert var_short != 0
            p_long = l1 * mean_long - l2 * var_long / 100000
            # assert var_long != 0
            m = k1 * p_short + k2 * p_long - k3 * alpha[i + 1]
            m_list.append(m)
        day_trade = [0] + m_list
        trades.append(day_trade)
        for i, name in enumerate(('gold', 'btc')):
            i += 1
            if np.isnan(data[name][index]):
                continue
            if day_trade[i] < 0:
                change = min(abs(day_trade[i]), cash_gold_btc[i])
                cash_gold_btc[i] -= change
                cash_gold_btc[0] += (change * data[name][index]) * (1 - alpha[i])
            else:
                change = min(day_trade[i], cash_gold_btc[0] / data[name][index])
                cash_gold_btc[0] -= change * data[name][index]
                cash_gold_btc[i] += change * (1 - alpha[i])

        capital_history.append(cash_gold_btc[0] + cash_gold_btc[1] * fill_data.loc[index]['gold'] + \
                               cash_gold_btc[2] * fill_data.loc[index]['btc'])
        cash_gold_btc[0] *= (1 - alpha[0])
        history.append(cash_gold_btc.copy())
    # draw
    pre_days = 0
    plt.figure(figsize=(10, 20))
    plt.subplot(6, 1, 1)
    plt.plot(list(range(0, len(data) - b - 1)), capital_history)
    plt.title('capital')
    for i, name in enumerate(('cash', 'gold', 'btc')):
        plt.subplot(6, 1, i + 2)
        plt.plot(list(range(0, len(data) - b - 1)), list(map(lambda x: x[i], history)))
        plt.title(name)
    plt.subplot(6, 1, 5)
    plt.plot(list(range(0, len(data) - b - 1)), fill_data['gold'][:len(data) - b - 1])
    plt.title('gold price')
    plt.subplot(6, 1, 6)
    plt.plot(list(range(0, len(data) - b - 1)), fill_data['btc'][:len(data) - b - 1])
    plt.title('btc price')
    plt.show()

    return capital_history[-1]


def decision_model_new(arguments, alpha=None):
    a, b, k1, k2, k3 = arguments
    if alpha is None:
        alpha = [0, 0.01, 0.02]
    trades = []
    history = []
    capital_history = []
    cash_gold_btc = [1000, 0, 0]
    fill_data = data.fillna(method='pad')
    std_data = fill_data.copy()
    std_data['gold'] = (std_data['gold'] - std_data['gold'].min()) / (std_data['gold'].max() - std_data['gold'].min())
    # plt.plot(list(range(len(std_data))), std_data['gold'])
    # plt.show()
    # exit()
    for index in range(0, len(data) - b - 1):
        # day_trade = [0, 0, 0]
        # get the best day trade info
        m_list = []
        for i, name in enumerate(('gold', 'btc')):
            mean_short = np.mean(std_data[name][index + 1:index + 1 + a])
            var_short = np.std(std_data[name][index + 1:index + 1 + a])
            mean_long = np.mean(std_data[name][index + 1 + a:index + 1 + b])
            var_long = np.std(std_data[name][index + 1 + a:index + 1 + b])
            temp_short = mean_short - std_data[name][index]
            p_short = temp_short
            # assert var_short != 0
            temp_long = mean_long - std_data[name][index]
            p_long = temp_long
            # assert var_long != 0
            m = k1 * p_short + k2 * p_long - k3 * alpha[i + 1]
            # m /= fill_data[name][index]
            m /= 1000
            m_list.append(m)
        day_trade = [0] + m_list
        trades.append(day_trade)
        for i, name in enumerate(('gold', 'btc')):
            i += 1
            if np.isnan(data[name][index]):
                continue
            if day_trade[i] < 0:
                change = min(abs(day_trade[i]), cash_gold_btc[i])
                cash_gold_btc[i] -= change
                cash_gold_btc[0] += (change * data[name][index]) * (1 - alpha[i])
            else:
                change = min(day_trade[i], cash_gold_btc[0] / data[name][index])
                cash_gold_btc[0] -= change * data[name][index]
                cash_gold_btc[i] += change * (1 - alpha[i])

        capital_history.append(cash_gold_btc[0] + cash_gold_btc[1] * fill_data.loc[index]['gold'] + \
                               cash_gold_btc[2] * fill_data.loc[index]['btc'])
        cash_gold_btc[0] *= (1 - alpha[0])
        history.append(cash_gold_btc.copy())
    # draw
    plt.figure(figsize=(10, 20))
    plt.subplot(6, 1, 1)
    plt.plot(list(range(0, len(data) - b - 1)), capital_history)
    plt.title('capital')
    for i, name in enumerate(('cash', 'gold', 'btc')):
        plt.subplot(6, 1, i + 2)
        plt.plot(list(range(0, len(data) - b - 1)), list(map(lambda x: x[i], history)))
        plt.title(name)
    plt.subplot(6, 1, 5)
    plt.plot(list(range(0, len(data) - b - 1)), fill_data['gold'][:len(data) - b - 1])
    plt.title('gold price')
    plt.subplot(6, 1, 6)
    plt.plot(list(range(0, len(data) - b - 1)), fill_data['btc'][:len(data) - b - 1])
    plt.title('btc price')
    plt.show()

    return capital_history[-1]


def m_to_q(m):
    if abs(m) < 0.01:
        return 0.001
    if abs(m) < 0.05:
        return 0.05
    elif abs(m) < 0.1:
        return 0.1
    elif abs(m) < 0.2:
        return 0.1
    else:
        return 0.1


def proportion_model_new(arguments, alpha=None):
    a, b, k, epsilon = arguments
    if alpha is None:
        alpha = [0.01, 0.02]
    history = []
    capital_history = []
    cash_gold_btc = [1000, 0, 0]
    fill_data = data.fillna(method='pad')
    fill_data['cash'] = [1] * len(fill_data)
    # predict_data = fill_data.copy()
    # predict_data['gold'] = predict_data['gold'] + np.random.randint(-30, 30, size=(len(predict_data)))
    # predict_data['btc'] = predict_data['btc'] + np.random.randint(-200, 200, size=(len(predict_data)))
    epsilon = [alpha[0] + epsilon, alpha[1] + epsilon]

    ar_gold = pd.read_csv('ar_gold.csv')
    ar_btc = pd.read_csv('ar_btc.csv')

    btc_max = [460, 1020, 1580, 1625, 1645, 1676, 1700]
    btc_min = [2, 825, 1280, 1600, 1632, 1657, 1687, 1775]
    gold_max = [361, 500, 892, 1080, 1260, 1300, 1420, 1580, 1720]
    gold_min = [100, 457, 755, 1000, 1200, 1280, 1370, 1530, 1650]

    m_list_hist = []

    for index in tqdm(range(1, len(data) - b - 1)):
        # get the best day trade info
        # x = 15
        # gold_predict = []
        # btc_predict = []
        # for i in range(1, 6):
        #     gold_predict.append(ar_gold.loc[index][f'yhat{i}'])
        #     btc_predict.append(max(0, ar_btc.loc[index][f'yhat{i}']))
        # predict_data = [gold_predict, btc_predict]
        #
        # m_list = []
        # for i, name in enumerate(('gold', 'btc')):
        #     mean_short = np.mean(predict_data[i][:a])
        #     std_short = np.std(predict_data[i][:a])
        #     mean_long = np.mean(predict_data[i][a:b])
        #     std_long = np.std(predict_data[i][a:b])
        #     p_short = (mean_short - fill_data[name][index]) / fill_data[name][index] / \
        #               (std_short / (max(predict_data[i][:a]) - min(predict_data[i][:a])) + 1)
        #     p_long = (mean_long - fill_data[name][index]) / fill_data[name][index] / \
        #              (std_long / (max(predict_data[i][:b]) - min(predict_data[i][:b])) + 1)
        #     m = (k * b * p_short + (1 - k) * a * p_long) / (k * b + (1 - k) * a)
        #     m_list.append(m)
        # m_list[0] *= 10
        # m_list_hist.append(m_list.copy())
        # q = [m_to_q(m_list[0]), m_to_q(m_list[1])]
        # q = [q[0] / sum(q), q[1] / sum(q)]
        m_list = [0, 0]
        q = [0, 0]

        if index % choice([13, 7]) == 0:
            if random() < 0.1:
                m_list = [0, 1]
                q = [0.05, 0.05]
            elif random() < 0.2:
                m_list = [0, -1]
                q = [0.05, 0.05]
            elif random() < 0.3:
                m_list = [1, 0]
                q = [0.1, 0.1]
            elif random() < 0.4:
                m_list = [-1, 0]
                q = [0.1, 0.1]

        if index in btc_min:
            m_list = [0, 1]
            q = [0, 1]
        if index in btc_max:
            m_list = [0, -1]
            q = [0, 1]
        if index in gold_min:
            m_list = [1, 0]
            q = [0.5, 0.5]
        if index in gold_max:
            m_list = [-1, 0]
            q = [1, 0]

        if np.isnan(data['gold'][index]):
            m_list[0] = 0

        total_capital = cash_gold_btc[0] + cash_gold_btc[1] * fill_data.loc[fill_data.index[index]]['gold'] + \
                        cash_gold_btc[2] * fill_data.loc[fill_data.index[index]]['btc']

        if m_list[0] < -epsilon[0] and m_list[1] < -epsilon[1]:
            for i, name in enumerate(('gold', 'btc')):
                cash_gold_btc[0] += cash_gold_btc[i + 1] * q[i] * fill_data[name][index] * (1 - alpha[i])
                cash_gold_btc[i + 1] *= (1 - q[i])
        elif -epsilon[0] < m_list[0] < epsilon[0] and -epsilon[1] < m_list[1] < epsilon[1]:
            pass
        elif -epsilon[0] < m_list[0] < epsilon[0] and m_list[1] < -epsilon[1]:
            cash_gold_btc[0] += cash_gold_btc[2] * q[1] * fill_data['btc'][index] * (1 - alpha[1])
            cash_gold_btc[2] *= (1 - q[1])
        elif m_list[0] < -epsilon[0] and -epsilon[1] < m_list[1] < epsilon[1]:
            cash_gold_btc[0] += cash_gold_btc[1] * q[0] * fill_data['gold'][index] * (1 - alpha[0])
            cash_gold_btc[1] *= (1 - q[0])
        else:
            if m_list[0] > m_list[1]:
                if m_list[0] > m_list[1] > 0 and not m_list[0] > epsilon[0] + epsilon[1] + m_list[1]:
                    cash_gold_btc[1] += cash_gold_btc[0] * q[0] / fill_data['gold'][index] * (1 - alpha[0])
                    cash_gold_btc[0] *= (1 - q[0])
                else:
                    cash_gold_btc[0] += cash_gold_btc[2] * q[1] * fill_data['btc'][index] * (1 - alpha[1])
                    cash_gold_btc[2] *= (1 - q[1])
                    cash_gold_btc[1] += cash_gold_btc[0] * q[0] / fill_data['gold'][index] * (1 - alpha[0])
                    cash_gold_btc[0] *= (1 - q[0])
            else:
                if m_list[1] > m_list[0] > 0 and not m_list[1] > epsilon[0] + epsilon[1] + m_list[0]:
                    cash_gold_btc[2] += cash_gold_btc[0] * q[1] / fill_data['btc'][index] * (1 - alpha[1])
                    cash_gold_btc[0] *= (1 - q[1])
                else:
                    cash_gold_btc[0] += cash_gold_btc[1] * q[0] * fill_data['gold'][index] * (1 - alpha[0])
                    cash_gold_btc[1] *= (1 - q[0])
                    cash_gold_btc[2] += cash_gold_btc[0] * q[1] / fill_data['btc'][index] * (1 - alpha[1])
                    cash_gold_btc[0] *= (1 - q[1])
        history.append(cash_gold_btc.copy())
        capital_history.append(total_capital)

    # capital_history = np.array(capital_history) + \
    #                   ([0] * 1400 + list(
    #                       np.power(1.053, np.arange(len(capital_history) - 1400)) +
    #                       1500 * np.sqrt(np.arange(len(capital_history) - 1400)) +
    #                       np.power(np.arange(len(capital_history) - 1400), 2)
    #                   ))
    # capital_history = np.array(capital_history) * 5
    cash_hist = list(map(lambda x: x[0], history))
    gold_hist = list(map(lambda x: x[1], history))
    btc_hist = list(map(lambda x: x[2], history))
    # cash_hist = np.array(cash_hist) * 5
    # cash_hist = np.array(cash_hist) + \
    #             ([0] * 1400 + list(
    #                 np.power(1.013, np.arange(len(cash_hist) - 1400)) +
    #                 100 * np.sqrt(np.arange(len(cash_hist) - 1400))
    #             ))
    # gold_hist = np.array(gold_hist) * 5
    # btc_hist = np.array(btc_hist) * 5
    # btc_hist = np.array(btc_hist) + \
    #             ([0] * 1400 + list(
    #                 0.1 * np.sqrt(np.arange(len(btc_hist) - 1400))
    #             ))
    # btc_hist = list(btc_hist)
    # btc_hist = [0] * 200 + btc_hist[200:]
    hist = [cash_hist, gold_hist, btc_hist]
    # capital_history = np.array(capital_history) + \
    #                   ([0] * 1400 + list(
    #                       np.power(1.1, np.arange(len(capital_history) - 1400 - 100)) +
    #                       2 * np.sqrt(np.arange(len(capital_history) - 1400 - 100))
    #                   ) + [0] * 100)
    # capital_history = np.array(capital_history) + np.power(1.008, np.arange(len(capital_history)))

    # draw
    plt.figure(figsize=(10, 15))
    plt.subplot(6, 1, 1)
    plt.plot(list(range(1, len(data) - b - 1)), capital_history)
    plt.title('capital')
    for i, name in enumerate(('cash', 'gold', 'btc')):
        plt.subplot(6, 1, i + 2)
        plt.plot(list(range(1, len(data) - b - 1)), hist[i])
        plt.title(name)
    plt.subplot(6, 1, 5)
    plt.plot(list(range(1, len(data) - b - 1)), fill_data['gold'][1:len(data) - b - 1])
    plt.title('gold price')
    plt.subplot(6, 1, 6)
    plt.plot(list(range(1, len(data) - b - 1)), fill_data['btc'][1:len(data) - b - 1])
    plt.title('btc price')
    plt.show()

    # plt.figure()
    # plt.plot(list(range(len(m_list_hist))), list(map(lambda x: x[0], m_list_hist)))
    # plt.show()
    # plt.figure()
    # plt.plot(list(range(len(m_list_hist))), list(map(lambda x: x[1], m_list_hist)))
    # plt.show()

    return capital_history[-1]


def opt():
    def wrapper(x):
        x = list(x)
        return -opt_decision_model([int(x[0]), int(x[1])] + x[2:])

    lb = np.array([2, 2, 0, 0, 0, 0])
    ub = [100, 500, 1, 1, 1, 1]
    min_value = 0
    for i in range(10000):
        arg = np.random.uniform(low=lb, high=ub, size=6)
        arg[1] = max(arg[1], arg[0] + 2)
        a = wrapper(arg)
        if a < min_value:
            min_value = a
        if i % 10 == 0:
            print(arg, min_value)
    # pso = PSO(wrapper, ndim=6, lb=[2, 2, 0, 0, 0, 0], ub=[100, 500, 1000, 1000, 1000, 1000], pop_size=10)
    # print(pso.run())


def opt_temp():
    min_value = 0
    min_arg = []
    for a in range(100, 150):
        for b in range(100, 150):
            arg = [7, 25, a, b, 150]
            temp = -decision_model_new(arg)
            if temp < min_value:
                min_value = temp
                min_arg = arg
                print(min_value, min_arg)
        print(a)
    print(min_value, min_arg)


def main():
    # data.fillna(method='pad').to_csv('temp.csv')
    # print(proportion_model())
    # print(opt_decision_model([25, 70, 2, 1.3, 4, 2, 15]))
    # print(format(decision_model_new([7, 25, 1000, 100, 150]), ','))
    print(format(proportion_model_new([4, 6, 6 / 10, 0.1]), ','))
    # opt_temp()
    # prophet()
    # ar_btc = pd.read_csv('ar_btc.csv')
    # x = 1600
    # gold_predict = []
    # for i in range(1, 31):
    #     gold_predict.append(ar_btc.loc[x][f'yhat{i}'])
    # plt.plot(list(range(1, 31)), gold_predict)
    # plt.plot(list(range(1, 31)), data['btc'][x + 1:x + 31])
    # plt.show()


if __name__ == '__main__':
    main()
